/*
 * @(#)HypertextUnit.java	1.0 08/01/07
 *
 * Copyright 2007 Fabio Gasparetti. All rights reserved.
 */

package org.tabularium.text.nlp;

import java.util.*;
import java.io.IOException;

import org.tabularium.text.nlp.wordnet.PartOfSpeech;

/**
 * In-memory implementation of the {@see CollectionFrequency} class based on
 * static arrays.
 * <p>
 * 
 * @TODO is still valid the statement: "Cannot be instantiated until someone
 *       provides the code to populate the internal array representation"?
 * 
 * @author Fabio Gasparetti
 * @version 1.0, 08/01/07
 */
public class ArrayCollectionFrequency implements CollectionFrequency {
	protected CollectionFrequency.TermFreq[] termFreqs = null;

	protected int numDocs = 0;

	public int getCollectionFrequency(String word, int pos) {
		CollectionFrequency.TermFreq tf = new CollectionFrequency.TermFreq(word
				.toUpperCase(), pos, 0);
		int idx = Arrays.binarySearch(termFreqs, tf);
		return idx > 0 ? termFreqs[idx].freq : 0;
	}

	public int getCollectionFrequency(String word) {
		int freq = 0; // ret
		CollectionFrequency.TermFreq tf;
		int idx;
		for (int pos = PartOfSpeech.MIN_POS; pos <= PartOfSpeech.MAX_POS; pos++) {
			tf = new CollectionFrequency.TermFreq(word.toUpperCase(), pos, 0);
			idx = Arrays.binarySearch(termFreqs, tf);
			if (idx >= 0) {
				freq += termFreqs[idx].freq;
			}
		}
		return freq;
	}

	public void load(String filename, CollectionFrequencyParser parser)
			throws IOException {
		List l = parser.read(filename);
		termFreqs = new CollectionFrequency.TermFreq[l.size()];
		CollectionFrequency.TermFreq tf;
		Iterator iter = l.iterator();
		int idx = 0;
		while (iter.hasNext()) {
			tf = (CollectionFrequency.TermFreq) iter.next();
			termFreqs[idx++] = tf;
		}
		numDocs = termFreqs[0].freq;
		Arrays.sort(termFreqs);
	}

	public int getCollectionSize() {
		return numDocs;
	}

	public int getNumberTerms() {
		return termFreqs.length;
	}

	public Iterator termFreqIterator() {
		return new ArrayCollectionFrequencyIterator(termFreqs);
	}

	public static void main(String args[]) throws Exception {
		try {
			ArrayCollectionFrequency f = new ArrayCollectionFrequency();
			BncParser p = new BncParser(new JwiStemmer());
			f.load("/home/fabio/projects/cues/idfs/all.num.o5", p);
			System.out.println(f.getCollectionSize());
			System.out.println(f.getCollectionFrequency("house"));
			System.out.println(f.getCollectionFrequency("house",
					PartOfSpeech.NOUN));
			System.out.println(f.getCollectionFrequency("house",
					PartOfSpeech.VERB));
			Iterator iter = f.termFreqIterator();
			int i = 0;
			int freq = 0;
			while (iter.hasNext()) {
				CollectionFrequency.TermFreq tf = ((CollectionFrequency.TermFreq) iter
						.next());
				System.out.println(++i + " " + tf.term + " "
						+ PartOfSpeech.toString(tf.pos) + " " + tf.freq);
				freq += tf.freq;
			}
			System.out.println(freq);
		} catch (Exception ex) {
			System.out.println(ex.toString());
			ex.printStackTrace();
		}
	}

}
